package team.nmsg.photo.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import team.nmsg.ge.system.bean.PageObject;
import team.nmsg.ge.system.bean.SysBusinessLog;
import team.nmsg.ge.system.controller.BaseController;
import team.nmsg.ge.system.init.CommonDefine;
import team.nmsg.ge.system.util.SysLanguageHelper;
import team.nmsg.photo.PhotoUtil;
import team.nmsg.photo.bean.FeaturePhoto;
import team.nmsg.photo.bean.PhotoBean;
import team.nmsg.photo.bean.ProjectBean;
import team.nmsg.photo.service.IPhotoService;

@CrossOrigin
@RestController
@RequestMapping("/photo")
public class PhotoController extends BaseController {
	
	private static Logger log = LoggerFactory.getLogger(PhotoController.class);
	
	@Autowired
	private IPhotoService photoService;

//	@RequestMapping("/uploadPhotos")
//	public String handleFileUpload(HttpServletRequest request, HttpServletResponse response,
//			@RequestParam("file") MultipartFile file) {
//		JSONObject obj = new JSONObject();
//		if (!file.isEmpty()) {
//			try {
//				String contextpath = System.getProperty("user.dir") + "/resources/photo";
//				File f = new File(contextpath);
//				if (!f.exists()) {
//					f.mkdirs();
//				}
//				String filename = file.getOriginalFilename();
//				String filepath = contextpath + "/" + filename;
//				file.transferTo(new File(filepath));
//			} catch (FileNotFoundException e) {
//				e.printStackTrace();
//				return "false";
//			} catch (IOException e) {
//				e.printStackTrace();
//				return "false";
//			}
//			writeJson(obj, response);
//			return null;
//		} else {
//			return "false";
//		}
//	}
	
	@RequestMapping("/uploadPhotos")
	public String handleFileUpload(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") MultipartFile file) {
		
		JSONObject obj = new JSONObject();
		
		String projectIdStr = request.getHeader("projectId");
		
		
		PhotoBean imgPath = photoService.saveImg( projectIdStr , file );
		
		writeJson(obj, response);
		return null;
	}
	
	@RequestMapping("/createProject")
	public String createProject(HttpServletRequest req, HttpServletResponse response , 
			@RequestParam("coverImg") MultipartFile coverImg ,
			@RequestParam("shareIconImg") MultipartFile shareIconImg ,
			@RequestParam("advertiseImg") MultipartFile advertiseImg ) {
		
		JSONObject obj = new JSONObject();
		
//		String projectSeq = req.getParameter("projectSeq");
//		String proTitle = req.getParameter("proTitle");
//		String proDesc = req.getParameter("proDesc");
//		String shareTitle = req.getParameter("shareTitle");
//		String shareDesc = req.getParameter("shareDesc");
//		String statusStr = req.getParameter("status");
//		String showFlag = req.getParameter("showFlag");
		
		String basicInfo = req.getParameter("basicInfo");
		
		ProjectBean pb = ProjectBean.fromJsonStr(basicInfo);
		
		String p1 = transferFile(coverImg);
		String p2 = transferFile(shareIconImg);
		String p3 = transferFile(advertiseImg);
		pb.setCoverImg(p1);
		pb.setShareIconImg(p2);
		pb.setAdvertiseImg(p3);
		
		
		pb = photoService.createProject(pb);
		
		if( pb!=null ) {
			obj.put("result", true);
		}else {
			obj.put("result", false );
		}
		
		writeJson(obj, response);
		return null;
	}
	
	private String transferFile( MultipartFile file1) {
		try {
			if( file1!=null && !file1.isEmpty() ) {
				String contextpath = PhotoUtil.tmpdir;
				File f = new File(contextpath);
				if (!f.exists()) {
					f.mkdirs();
				}
				String sfilename = file1.getOriginalFilename();
				String filename = UUID.randomUUID().toString().replace("-", "") + PhotoUtil.getSuffixWithDot(sfilename);
				String filepath = contextpath + "/" + filename;
				file1.transferTo(new File(filepath));
				
				return filepath;
			}
		} catch ( Exception e) {
			log.error( ""  , e);
		}  
		return "";
	}

	
	@RequestMapping("/queryProjectInfo")
	public String queryProjectInfo(HttpServletRequest req, HttpServletResponse resp ) {
		
		String projectIdStr = req.getParameter("projectId");
		JSONObject obj = new JSONObject();
		
		ProjectBean pb = photoService.getProject(Long.parseLong(projectIdStr));
		
		obj.put( "result" ,  true );
		obj.put( "pro" ,  pb.toJson() );
		writeJson(obj, resp);
		return null;
	}
		
	@RequestMapping("/queryProjectByPage")
	public String queryProjectByPage(HttpServletRequest req, HttpServletResponse resp  ) {
		JSONObject obj = new JSONObject();
		
		
		String pageSize = req.getParameter("pageSize");
		String currentPage = req.getParameter("currentPage");
		int startIndex = 0;
		startIndex = Integer.parseInt(pageSize) * (Integer.parseInt(currentPage) - 1);

		
		String proTitle = req.getParameter("proTitle");
		String projectSeq = req.getParameter("projectSeq");
		ProjectBean criteria = new ProjectBean();
		criteria.setProTitle(proTitle);
		criteria.setProjectSeq(projectSeq);
		
		PageObject<ProjectBean> page = photoService.getProjects( criteria, Integer.parseInt(pageSize), startIndex );
		
		JSONArray arr = new JSONArray();
		for (ProjectBean bean : page.getCurrentEntitys()) {
			JSONObject json = bean.toJson();
			arr.add(json);
		}

		obj.put("data", arr);
		obj.put("total", page.getSumCount());
		
		obj.put( "result" ,  true );
		writeJson(obj, resp);
		return null;
	}
	
	
	@RequestMapping("/setProjectVisiable")
	public String getProjectInfoByPage(HttpServletRequest req, HttpServletResponse resp  ) {
		JSONObject obj = new JSONObject();
		
		String projectIdStrs = req.getParameter("projectIds");
		String isShow = req.getParameter("isShow");
		
		photoService.setProjectsIsShow(  projectIdStrs , Boolean.parseBoolean(isShow)  );
		
		obj.put( "result" ,  true );
		writeJson(obj, resp);
		return null;
	}
	
	@RequestMapping("/setProjectFinished")
	public String setProjectFinished(HttpServletRequest req, HttpServletResponse resp  ) {
		JSONObject obj = new JSONObject();
		
		String projectIdStrs = req.getParameter("projectIds");
		
		photoService.setProjectsFinished(  projectIdStrs  );
		
		obj.put( "result" ,  true );
		writeJson(obj, resp);
		return null;
	}
	
	@RequestMapping("/delProjects")
	public String delProjects(HttpServletRequest req, HttpServletResponse resp  ) {
		JSONObject obj = new JSONObject();
		
		String projectIdStrs = req.getParameter("projectIds");
		
		photoService.delProjects(  projectIdStrs  );
		
		obj.put( "result" ,  true );
		writeJson(obj, resp);
		return null;
	}
	
	@RequestMapping("/editProject")
	public String editProject(HttpServletRequest req, HttpServletResponse resp  ) {
		JSONObject obj = new JSONObject();
		
		String proInfo = req.getParameter("proInfo");
		
		ProjectBean pb = ProjectBean.fromJsonStr(proInfo);
		
		photoService.editProject(  pb  );
		
		obj.put( "result" ,  true );
		writeJson(obj, resp);
		return null;
	}
	
	@RequestMapping("/editProjectPic")
	public String editProjectPic(HttpServletRequest req, HttpServletResponse resp ,
			@RequestParam("img") MultipartFile img  ) {
		JSONObject obj = new JSONObject();
		
		String utype = req.getParameter("utype");
		String pid = req.getParameter("pid");
		
		String newImg = transferFile(img);
		
		String newpath = photoService.editProjectPic(  utype , pid , newImg );
		
		obj.put( "result" ,  true );
		obj.put( "newpath" ,  newpath );
		obj.put( "t" ,  System.currentTimeMillis() );
		writeJson(obj, resp);
		return null;
	}
	
	@RequestMapping("/delAPhotoFromProject")
	public String delAPhotoFromProject(HttpServletRequest req, HttpServletResponse resp  ) {
		JSONObject obj = new JSONObject();
		
		String projectIdStr = req.getParameter("proId");
		String photoIdStr = req.getParameter("photoId");
		
		photoService.delPhoto(  projectIdStr  , photoIdStr );
		
		obj.put( "result" ,  true );
		writeJson(obj, resp);
		return null;
	}
	
	@RequestMapping("/addToFeature")
	public String addToFeature(HttpServletRequest req, HttpServletResponse resp  ) {
		JSONObject obj = new JSONObject();
		
		String projectIdStr = req.getParameter("proId");
		String photoIdStr = req.getParameter("photoId");
		String path = req.getParameter("path");
		String path2 = req.getParameter("path2");
		String desc = req.getParameter("desc");
		
		FeaturePhoto featurePhoto = new FeaturePhoto();
		featurePhoto.setProId(Long.parseLong(projectIdStr));
		featurePhoto.setPhotoId(Long.parseLong(photoIdStr));
		featurePhoto.setPhotoPath(path);
		featurePhoto.setPhotoPath2(path2);
		featurePhoto.setFeatureDesc(desc);
		
		FeaturePhoto addFeature = photoService.addFeature(  featurePhoto );
		
		obj.put( "result" ,  true );
		obj.put( "d" ,  addFeature.toJson() );
		writeJson(obj, resp);
		return null;
	}
	
	@RequestMapping("/getFeatures")
	public String getFeatures(HttpServletRequest req, HttpServletResponse resp  ) {
		JSONObject obj = new JSONObject();
		
		FeaturePhoto featurePhoto = new FeaturePhoto();
		List<FeaturePhoto> fs = photoService.getFeatures(  featurePhoto );
		
		JSONArray arr = new JSONArray();
		for (FeaturePhoto bean :  fs ) {
			JSONObject json = bean.toJson();
			arr.add(json);
		}
		
		obj.put( "result" ,  true );
		obj.put( "arr" ,  arr );
		
		
		writeJson(obj, resp );
		return null;
	}
	
	@RequestMapping("/delFeature")
	public String delFeature(HttpServletRequest req, HttpServletResponse resp  ) {
		JSONObject obj = new JSONObject();
		
		String parameter = req.getParameter("fId");
		FeaturePhoto featurePhoto = new FeaturePhoto();
		featurePhoto.setfId(Long.parseLong( parameter ) );
		
		boolean res = photoService.delAFeature(  featurePhoto  );
		
		obj.put( "result" ,  true );
		writeJson(obj, resp );
		return null;
	}
	
	//重置 所有 项目 顺序
	@RequestMapping("/resetPOrder")
	public String resetPOrder(HttpServletRequest req, HttpServletResponse resp  ) {
		JSONObject obj = new JSONObject();
		
		
		boolean res = photoService.resetPOrder(   );
		
		obj.put( "result" ,  res );
		writeJson(obj, resp );
		return null;
	}
	
	
	@RequestMapping("/temp")
	public String temp(HttpServletRequest req, HttpServletResponse resp  ) {
		JSONObject obj = new JSONObject();
		
		writeJson(obj, resp );
		return null;
	}

	
}
